//
//  EMLoginViewController.swift
//  Hyphenate-Demo-Swift
//
//  Created by dujiepeng on 2017/6/13.
//  Copyright 2017 dujiepeng. All rights reserved.
//

import UIKit
import MBProgressHUD
import Hyphenate
class EMRegisterViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var usernameTextField: UITextField!
    @IBOutlet weak var loginButton: UIButton!
    @IBOutlet weak var getCode: UIButton!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var phoneOrEmailTextField: UITextField!
    @IBOutlet weak var RepasswordTextField: UITextField!
    @IBOutlet weak var codeTextField: UITextField!
    @IBOutlet weak var loginView: UIView!
    
    @IBOutlet weak var countryCode: UITextField!
    @IBAction func goBack(_ sender: UIBarButtonItem) {
        dismiss(animated: true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setBackgroundColor()
        setupUI()
//        setupForDismissKeyboard()
//        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
    }
    
    func setupUI () {
        usernameTextField.delegate = self
        usernameTextField.leftView = UIView.init(frame: CGRect(x: 0, y: 0, width: 15, height: usernameTextField.height()))
        usernameTextField.leftViewMode = UITextFieldViewMode.always
        
        phoneOrEmailTextField.delegate = self
        phoneOrEmailTextField.leftView = UIView.init(frame: CGRect(x: 0, y: 0, width: 15, height: phoneOrEmailTextField.height()))
        phoneOrEmailTextField.leftViewMode = UITextFieldViewMode.always
        
        countryCode.delegate = self
        countryCode.leftView = UIView.init(frame: CGRect(x: 0, y: 0, width: 15, height: phoneOrEmailTextField.height()))
        countryCode.leftViewMode = UITextFieldViewMode.always
        
        
        passwordTextField.delegate = self
        passwordTextField.leftView = UIView.init(frame: CGRect(x: 0, y: 0, width: 15, height: passwordTextField.height()))
        passwordTextField.leftViewMode = UITextFieldViewMode.always
        
        RepasswordTextField.delegate = self
        RepasswordTextField.leftView = UIView.init(frame: CGRect(x: 0, y: 0, width: 15, height: RepasswordTextField.height()))
        RepasswordTextField.leftViewMode = UITextFieldViewMode.always
        
        codeTextField.delegate = self
        codeTextField.leftView = UIView.init(frame: CGRect(x: 0, y: 0, width: 15, height: codeTextField.height()))
        codeTextField.leftViewMode = UITextFieldViewMode.always
        
        loginButton.top(top: kScreenHeight - loginButton.height())
        loginButton.width(width: kScreenWidth)
        
    }
    
    func setBackgroundColor () {
        let gradient = CAGradientLayer.init()
        gradient.frame = UIScreen.main.bounds
        gradient.colors =  [LaunchTopColor.cgColor, LaunchBottomColor.cgColor]
        gradient.startPoint = CGPoint.init(x: 0.0, y: 0.0)
        gradient.endPoint = CGPoint.init(x: 0.0, y: 1.0)
        view.layer.insertSublayer(gradient, at: 0)
    }
    
    @IBAction func getCode(_ sender: UIButton) {
        if ((phoneOrEmailTextField.text!.count) == 0 || (countryCode.text!.count) == 0) {
            self.show("please input your Phone Or Email".localized())
            return
        }
        MBProgressHUD.showAdded(to: view, animated: true)
        weak var weakSelf = self
        
        let parameters = [
            "registerType": "newAccount",
            "phone":phoneOrEmailTextField.text!,
            "countryCode":countryCode.text!.replacingOccurrences(of: "+", with: "", options: .literal, range: nil)
            ]
        CUHTTP.instance().makePostData(url: "code", parameters:parameters, success: { (response) in
            MBProgressHUD.hide(for: weakSelf?.view, animated: true)
            self.show("Code Sent".localized())
        }) { (response) in
            MBProgressHUD.hide(for: weakSelf?.view, animated: true)
            self.show(response ?? "")
        }
    }
    @IBAction func doLogin(_ sender: UIButton?) {
        if _isEmpty() {
            return
        }
        
        MBProgressHUD.showAdded(to: view, animated: true)
        weak var weakSelf = self
        
        let md5Password = md5(String(passwordTextField.text!))
        let username = usernameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        let code = String(codeTextField.text!)
        let parameters = [
            "username": username,
            "phone":phoneOrEmailTextField.text!,
            "countryCode":countryCode.text!.replacingOccurrences(of: "+", with: "", options: .literal, range: nil),
            "code":code,
            "deviceType":"1",
            "registerType":"newAccount",
            "password":md5Password
        ]
        
        CUHTTP.instance().makePostData(url: "register", parameters:parameters, success: { response in
            MBProgressHUD.hide(for: weakSelf?.view, animated: true)
            var alertStr = ""
            alertStr = "Registration Successful".localized()
            let alertView = UIAlertView.init(title: nil, message: alertStr, delegate: nil, cancelButtonTitle: "okay")
            alertView.show()
            // API call is Successfull
            self.dismiss(animated: true, completion: nil)
            
        }, failure: { response in
            MBProgressHUD.hide(for: weakSelf?.view, animated: true)
            
            let alertView = UIAlertView.init(title: nil, message: response, delegate: nil, cancelButtonTitle: "okay")
            alertView.show()
            
            // API call Failure
            
        })
    }
    
    func md5(_ string: String) -> String {
        let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1)
        var digest = Array<UInt8>(repeating:0, count:Int(CC_MD5_DIGEST_LENGTH))
        CC_MD5_Init(context)
        CC_MD5_Update(context, string, CC_LONG(string.lengthOfBytes(using: String.Encoding.utf8)))
        CC_MD5_Final(&digest, context)
        context.deallocate(capacity: 1)
        var hexString = ""
        for byte in digest {
            hexString += String(format:"%02x", byte)
        }
        return hexString
    }
    // MARK: - private
    
    fileprivate func _isEmpty() -> Bool {
        
        let username = usernameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        let password = passwordTextField.text
        let code = codeTextField.text
        let repassword = RepasswordTextField.text
        if repassword != password {
            let alertView = UIAlertView.init(title: "reminder".localized(), message: "Inconsistent password".localized(), delegate: nil, cancelButtonTitle: "okay")
            alertView.show()
            
            return true
        }
        if (username?.count)! == 0 || (password?.count)! == 0 ||
            (countryCode.text!.count) == 0 ||  (phoneOrEmailTextField.text!.count) == 0 || (code?.count)! == 0 {
            let alertView = UIAlertView.init(title: "reminder".localized(), message: "Incomplete information".localized(), delegate: nil, cancelButtonTitle: "okay")
            alertView.show()
            
            return true
        }
        
        if !(isValidUname(testStr: username!)) {
            let alertView = UIAlertView.init(title: "reminder".localized(), message: "invalid usernmame".localized(), delegate: nil, cancelButtonTitle: "okay")
            alertView.show()
            
            return true
        }
        return false
    }
    
    func isValidUname(testStr:String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._]{1,64}"
        
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: testStr)
    }
    
    // MARK: - notification
//    @objc func keyboardWillChangeFrame(noti: NSNotification) {
//        let userInfo = (noti.userInfo as! Dictionary<String, NSValue>)
//        let beginValue = userInfo["UIKeyboardFrameBeginUserInfoKey"]!
//        let endValue = userInfo["UIKeyboardFrameEndUserInfoKey"]!
//        
//        var beginRect = CGRect()
//        var endRect = CGRect()
//        beginValue.getValue(&beginRect)
//        endValue.getValue(&endRect)
//        
//        var btnFrame = CGRect()
//        var top: CGFloat = 0
//        
//        btnFrame = loginButton.frame
//        
//        
//        if endRect.origin.y == view.height() {
//            btnFrame.origin.y = kScreenHeight - btnFrame.size.height
//        } else if (beginRect.origin.y == view.height()) {
//            btnFrame.origin.y = kScreenHeight - btnFrame.size.height - endRect.size.height + 100
//            top = -100
//        } else {
//            btnFrame.origin.y = kScreenHeight - btnFrame.size.height - endRect.size.height + 100
//            top = -100
//        }
//        
//        weak var weakSelf = self
//        UIView.animate(withDuration: 0.3) {
//            UIApplication.shared.keyWindow?.top(top: top)
//            weakSelf?.loginButton.frame = btnFrame
//        }
//        
//    }
}
